<script setup lang="ts">
  import { onMounted, ref, shallowRef, useTemplateRef } from 'vue';
  import { useCesium } from '@/hooks/useCesium';
  import { buildingData } from './data.json';
  import { ElLoading, ElMessage } from 'element-plus';
  import { v4 } from 'uuid';
  import { useFileDialog } from '@vueuse/core';
  import MyGrawer from './MyGrawer.vue';
  import { FusionData, BuildingDataType, UserDataType } from '@/hooks/FusionData';
  import { processExcelFile } from '@/hooks/utils';

  const myGrawerDom = useTemplateRef('myGrawerDom');

  const fusionData = shallowRef<FusionData | null>(null);

  const { open, onChange } = useFileDialog({
    accept: '.xls,.xlsx'
  });
  onChange(async files => {
    const file = files![0];
    console.log(files);
    userDataOrigin.value = await processExcelFile(file).then((res: any) => {
      return res.map(item => {
        const floorNumber = item.room_number?.toString().slice(0, -2) || '';
        return {
          id: item.id,
          buildingNumber: item.building_number,
          unitNumber: '_单元号',
          floorNumber,
          roomNumber: item.room_number,
          fullRoomId: `${item.xqname ?? ''}-${item.building_number ?? ''}-${
            item.room_number ?? ''
          }`, //'安滨嘉苑-D1-206',
          address: `${item.xqname}${item.building_number}${item.room_number}`, //'安滨嘉苑D1栋206室',
          community: item.xqname, //'安滨嘉苑',
          ownerInfo: {
            name: item.actual_resident, //'李四',
            idCard: `idCard_${item.actual_resident}`,
            phone: item.tel
          },
          propertyInfo: {
            // area: 116.65659154474933,
            // propertyType: '商业',
            // condition: '待售'
          }
          // coordinates: {
          //   longitude: 120.62138434769074,
          //   latitude: 30.161340249147447
          // }
        };
      });
    });
    ElMessage.success('加载权属数据成功,一共' + userDataOrigin.value.length + '条数据');
  });

  const onClickCb = (location: any) => {
    // const data = fusionData.value?.cesiumPointDistance(location);

    //以下是采用kd树进行空间查询
    const data = fusionData.value?.searchPosition(location);

    myGrawerDom.value?.open(data);
    return data?.details.buildData;
  };

  const { target, initViewer, load } = useCesium({ onClickCb });

  const buildingDataOrigin = ref<BuildingDataType[]>([]);
  const userDataOrigin = ref<UserDataType[]>([]);

  const loadBimData = () => {
    buildingDataOrigin.value = buildingData
      .map(item => {
        const uuid = v4();
        const { 0: community, 1: buildingNumber, 2: roomNumber } = item.id?.split('-') || [];
        const floorNumber = roomNumber.slice(0, -2) || '';
        const position = {
          latitude: item.lat,
          longitude: item.lng
        };

        return {
          ...item,
          originalId: item.id,
          uuid,
          buildingNumber: buildingNumber ?? '', // 楼栋号
          roomNumber: roomNumber ?? '', // 房间号
          community: community ?? '', // 小区名
          floorNumber, // 楼层号
          position // 位置
        };
      })
      .filter(item => item.id.includes('兴海嘉苑'));

    // .slice(0, 2);
    ElMessage.success('兴海嘉苑' + buildingDataOrigin.value.length + '条数据');
  };

  const startFusion = async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '数据融合中，请稍等',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    // 融合数据
    const fd = new FusionData({
      buildingData: buildingDataOrigin.value,
      userData: userDataOrigin.value
    });
    await fd.handleDataCleaning();
    ElMessage.success('数据清理完成');

    // 运行融合数据
    const res = fd.runFusionData();
    ElMessage.success('融合数据成功,一共融合了' + res.length + '条数据');
    fusionData.value = fd;
    loading.close();
  };

  const upload = () => {
    fusionData.value?.downloadJSON();
  };

  onMounted(() => {
    initViewer();
  });
</script>

<template>
  <el-container>
    <el-aside style="width: fit-content">
      <div class="flex flex-col gap-[10px]">
        <el-button type="primary" @click="load">加载模型数据</el-button>
        <el-button type="primary" @click="loadBimData">加载空间数据</el-button>
        <el-button type="primary" @click="open()">加载用户数据</el-button>
        <el-button type="primary" @click="startFusion">开始数据融合</el-button>
        <el-button type="primary" @click="upload">导出融合后的数据</el-button>
        <!-- <el-button type="primary" @click="onClickCb">显示碳层</el-button> -->
      </div>
    </el-aside>
    <el-container>
      <el-main style="--el-main-padding: 0" class="flex overflow-hidden">
        <div id="cesiumContainer" class="h-[100vh]" ref="target"></div>
        <router-view />
      </el-main>
    </el-container>
  </el-container>
  <MyGrawer ref="myGrawerDom" />
</template>

<style scoped lang="less"></style>
